package com.gyf.backoffice.web.controller;


import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.UUID;

@Controller
@RequestMapping("upload")
public class UploadController {

    @RequestMapping("itemspic")
    public void itemspic(HttpServletRequest request, MultipartHttpServletRequest multipartHttpServletRequest,
                         String fileName, PrintWriter writer, HttpServletResponse response)throws Exception{

        //通过字段名获取图片数据
        MultipartFile fileC = multipartHttpServletRequest.getFile(fileName);
        System.out.println(fileName + "文件大小--" + fileC.getSize());//29074

        String saveName = UUID.randomUUID().toString();
        //itemspic1
        //文件保存目录
        String uploadFolder = request.getSession().getServletContext().getRealPath("/upload");

        //判断文件是否存在
        File uoloadFolderFile = new File(uploadFolder);
        if(!uoloadFolderFile.exists()){
            uoloadFolderFile.mkdirs();
        }

        //新图片名
        String suffix = fileC.getOriginalFilename().split("\\.")[1];
        //jpg
        String saveFileName = saveName.replace("-","") + "." + suffix;
        //50eb7916f6fa4f019301f2f2558d747b.jpg
        //图片路径 = 文件夹目录 + 新图片名
        String totalPath = uploadFolder + "\\" + saveFileName;

        File newFile = new File(totalPath);

        //2.把图片保存到某个路径中
         FileCopyUtils.copy(fileC.getInputStream(), new FileOutputStream(newFile));


        //返回数据给客户端
        String imgUrl = "http://localhost:8080/upload/" + saveFileName;
        String responseJson = "{\"imgUrl\":\"" + imgUrl  + "\"}";
        response.setHeader("content-type", "text/json;charset=utf-8");
        response.getWriter().write(responseJson);





    }
}
